package com.ktwlsoft.archivemanage.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@ConditionalOnProperty(name = "app.cors.enabled", havingValue = "true")
@Configuration
public class CorsConfig {

    @Autowired
    private CorsProperty corsProperty;

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1允许任何域名使用
        for(String item : corsProperty.getAllowedOrigins()){
            corsConfiguration.addAllowedOrigin(item);
        }
        // 2允许任何头
        for(String item : corsProperty.getAllowedHeaders()){
            corsConfiguration.addAllowedHeader(item);
        }
        // 3允许任何方法（post、get等）
        for(String item : corsProperty.getAllowedMethods()){
            corsConfiguration.addAllowedMethod(item);
        }
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(corsProperty.getFilterPath(), buildConfig());
        return new CorsFilter(source);
    }
}
